/**
 * 
 */
package com.atjava.nebula.core.dao.ibatis.projection;

import java.util.ArrayList;
import java.util.List;

/**用于保存多个投影的列表
 * @author kyo
 *
 */
public class ProjectionList implements IProjection{
	String having=null;
	List<IProjection> projectionList=new ArrayList<IProjection>();
	/**加入新的投影
	 * @param projection Projection类型的投影对象，
	 * 一般通过Projections.sum("value")方式创建
	 * @return 返回当前ProjectionList
	 */
	public ProjectionList add(IProjection projection){
		projectionList.add(projection);
		return this;
	}
	/**分组时的having条件
	 * @param having 条件字符串（不需要传入"having"关键字）
	 * @return 返回当前ProjectionList
	 */
	public ProjectionList having(String having){
		this.having = having;
		return this;
	}
	public List<IProjection> getProjectionList() {
		return projectionList;
	}
	/* 
	 * @see com.atjava.nebula.core.dao.ibatis.projection.IProjection#toSqlString()
	 */
	public String toSqlString() 
	{
		StringBuffer buf = new StringBuffer();
		for ( int i=0; i<getLength(); i++ ) {
			IProjection proj = getProjection(i);
			buf.append( proj.toSqlString() );
			if ( i<getLength()-1 ) buf.append(", ");
		}
		return buf.toString();
	}
	
	/* 
	 * @see com.atjava.nebula.core.dao.ibatis.projection.IProjection#toGroupSqlString()
	 */
	public String toGroupSqlString() 
	{
		StringBuffer buf = new StringBuffer();
		for ( int i=0; i<getLength(); i++ ) {
			IProjection proj = getProjection(i);
			if ( proj.isGrouped() ) {
				buf.append( proj.toGroupSqlString() ).append(", ");
				
			}
			
		}
		if ( buf.length()>2 ) buf.setLength( buf.length()-2 ); //pull off the last ", "
		if(having != null){
			buf.append(" having ").append(having);
		}
		return buf.toString();
	}	
	public int getLength() {
		return projectionList.size();
	}	
	public IProjection getProjection(int i) {
		return (IProjection) projectionList.get(i);
	}	
	/* 
	 * @see com.atjava.nebula.core.dao.ibatis.projection.IProjection#isGrouped()
	 */
	public boolean isGrouped() {
		for ( int i=0; i<getLength(); i++ ) {
			if ( getProjection(i).isGrouped() ) return true;
		}
		return false;
	}	
}
